import React, {PureComponent} from 'react';
import {Menu, Icon} from 'antd';
import {Link} from 'react-router-dom';
import PropTypes from 'prop-types';

import {arrayToTree} from '@/utils'

const {Item, SubMenu} = Menu

class Menus extends PureComponent {
  static propTypes = {
    menus: PropTypes.array,
    location: PropTypes.any
  }

  constructor(props) {
    super(props);
    this.state = {
      defaultSelectedKeys: [],
      defaultOpenKeys: [],
      menuTreeData: [], // 菜单数据（层级）
      menuTreeDom: []  // 生成的菜单结构
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.menus !== nextProps.menus) {
      this._getMenuTreeData(nextProps.menus);
    }
    if (this.props.location !== nextProps.location) {
      this._getSelectedMenus(nextProps.location);
    }
  }

  componentDidMount() {
    this._getMenuTreeData(this.props.menus);
    this._getSelectedMenus(this.props.location);
  }

  _getMenuTreeData(data) {
    if (data) {
      let menuTreeData = arrayToTree(data.filter(item => item.mpid !== '-1'), 'id', 'mpid')
      this.setState({
        menuTreeData
      })
    }
  }

  _getMenuItems(menuTreeN) {
    return menuTreeN.map(item => {
      if (item.children) {
        return (
          <SubMenu key={item.route} title={
            <span>
            {item.icon && <Icon type={item.icon}/>}
              {item.name}
          </span>
          }>
            {this._getMenuItems(item.children)}
          </SubMenu>
        )
      }
      return (
          <Item key={item.route}>
            <Link to={item.route || '#'} style={{width: 10}}>
              {item.icon && <Icon type={item.icon}/>}
              {item.name}
            </Link>
          </Item>
      )
    })
  }

  _getSelectedMenus(location) {
    const paths = location.pathname.split('/').filter(item => !!item);
    this.setState({
      defaultSelectedKeys: [location.pathname],
      defaultOpenKeys: paths.map(item => `/${item}`)
    })
  }

  handleOpenChange(keys) {
    this.setState({
      defaultOpenKeys: keys
    })
  }

  render() {
    const menuItems = this._getMenuItems(this.state.menuTreeData)
    return (
      <Menu
        theme="light"
        mode="inline"
        defaultSelectedKeys={this.state.defaultSelectedKeys}
        defaultOpenKeys={this.state.defaultOpenKeys}
        selectedKeys={this.state.defaultSelectedKeys}
        openKeys={this.state.defaultOpenKeys}
        onOpenChange={this.handleOpenChange.bind(this)}
        style={{height: '100%', borderRight: 0}}
      >
        {menuItems}
      </Menu>
    )
  }
}

export default Menus
